/**
 * 合同界面
 */
var currentpage=1;
$(document).ready(function(){	
	//点击弹出模态框，创建合同
	$(document).delegate('.addBtn', 'click', function() {

		$('#addContract').modal('show');
		//$("body").css("padding-right",0);
	});
	//模态框创建合同之提交事件
	$("#addContractForm").bind("submit",function(){
		//alert("1232223");
		var data = new FormData($('#addContractForm')[0]);
		/*data.append("conName",$("#conName1").val());
		data.append("conType",$("#conType1").val());
		data.append("conPartyA",$("#conPartyA1").val());
		data.append("conPartyB",$("#conPartyB1").val());
		data.append("conBusinessNumA",$("#conBusinessNumA1").val());
		data.append("conBusinessNumB",$("#conBusinessNumB1").val());
		data.append("conContext",$("#conContext1").val());
		data.append("conRemark",$("#conRemark1").val());*/
		var options = {				
				url:'../contract/insertContract',
				type:'post',
				dataType:'text',
				data:data,
				processData: false,
				contentType: false,
				success:function(data){
					$("#addContract").modal('hide');
					if("1"==data){
						jBox.tip("添加成功！！","success");
					}else{
						jBox.tip("添加失败！！","error");
					}
					/*$("#conName1").val("");
					$("#conType1").val("");
					$("#conPrice1").val("");
					$("#conPartyA1").val("");
					$("#conPartyB1").val("");
					$("#conBusinessNumA1").val("");
					$("#conBusinessNumB1").val("");
					$("#conContext1").val("");
					$("#conRemark1").val("");*/					
					//清空表单数据
					$("#addContractForm")[0].reset();
				}
		}
		$.ajax(options);
		return false;
	});
	//模态框点击提交
	$('#btnAddsubmit').click(function(){
		//alert("asdsad");
        $('#addContractForm').submit();
   });
	//点击全选改变
	$("#checkall").click(function(){				
		 $(".check_item").each(function() {	
			 if(!$(this).prop("disabled")){
				 $(this).prop("checked",$("#checkall").prop("checked"));	
			 }
		 });
	});
})

//下边的checkbox全选时上边的checkbox的checked属性为true
$(document).on("click",".check_item",function(){
	//判断当前选中的元素有几个，如果为总元素的个数则总元素状态为true，否则为false
	//当前为5个，为了页面的扩展性，此处判断不写为静态的值，而是动态判断
	var flag = $(".check_item:checked").length ==$(".check_item").length ;
	$("#checkall").prop("checked",flag);
});

//点击提交按钮，可进行批量提交
var theArray = [];
$(document).delegate('.submmitBtn','click',function() {
	  
		//alert(11);
	   $(".check_item:checked").each(function() { 
		      theArray.push($(this).parents("td").prop("contract-id"));
		      console.log("////////"+theArray[0]);		    
	   });
	   //处理请求参数，合同id
	   var params ="";
	   for(var i = 0; i<theArray.length;i++){
			params+=theArray[i]+"&";
	   }
	   //alert(params);
	   params= params.substring(0,params.length-1);	   
	   if(theArray.length<1){
		   jBox.tip("请至少选择一个","warning");
	   }else{
		   if(confirm("确认要提交吗？")){			  
			  //发送ajax请求，改变合同状态
			   $.ajax({
					url : '../contract/updateState',
					async : true,
					type : "post",
					data:{"params":params},
					dataType : "text",
					cache : false, // 不允许缓存
					success : function(result) {
						if (result=="success") {
							jBox.tip("提交成功!!","success");							
							listContract(currentpage);
						} else {
							jBox.tip("提交失败!!","error");
						}

					},
					error : function(result) {
						jBox.tip("提交失败!!","error");
					} 
				});
			   
		   }else{
			   theArray = [];
		   }
		   
	   }
});

//查询合同

function listContract(currentpage){	
	
	$.ajax({
		url:'../contract/listContract',
		type:'get',
		data:{'currentpage':currentpage},
		dataType:'json',
		success:function(result){	
			console.log(result);
			currentpage = result.pageInfo.pageNum;
			$("#conTable tbody").html("");
			$.each(result.contractList,function(index,item){							
				
				if(item.conState=="已订立" || item.conState=="已打回"){				
					var checkBoxTd = $("<td><input type='checkbox' class='check_item'></td>");
				}else{
					var checkBoxTd = $("<td><input type='checkbox' class='check_item' disabled='disabled'></td>");
				}			
				var conNameTd = $("<td></td>").append(item.conName);
				var conTypeTd = $("<td></td>").append(item.conType);
				var conStateTd = $("<td class='conState'></td>").append(item.conState);
				var conConLatestOpreationTimeTd = $("<td></td>").append(item.conLatestOpreationTime);
				var conNextHandlerTd = $("<td></td>").append(item.conNextHandeler);
				
				var editTd = $("<button></button>").addClass("btn btn-info btn-xs active edit_btn").append("编辑");
				//为编辑按钮添加自定义的属性，属性值设置为合同的ID方便修改是查找合同信息用于模态框的显示
				editTd.attr("edit-id",item.contractId);
				editTd.val(item.contractId);
				//给复选框id
				checkBoxTd.prop("contract-id",item.contractId);
				//删除按钮
				var delTd = $("<button></button>").addClass("btn btn-warning btn-xs active delete_btn").append("删除");
				delTd.attr("delete-id",item.contractId);
				var btnTd = $("<td></td>").append(editTd).append("  ").append(delTd);
								
				$("<tr class='active'></tr>").append("<td></td")
							.append(checkBoxTd)
							.append(conNameTd)
							.append(conTypeTd)
							.append(conStateTd)
							.append(conConLatestOpreationTimeTd)
							.append(conNextHandlerTd)
							.append(btnTd)
							.appendTo("#conTable tbody");		
			});
			laypage({
				 cont:'fenye',//容器
			     pages:result.pages, //总页数
			     //limit:2,//每页显示的条数
			     curr:currentpage,//当前页
			     skin:'molv',//皮肤
			     skip:true,//
			     last:'尾页',//
			     jump:function(obj,first){
			    	 currentpage=obj.curr;
			    	     if(!first){
			    	    	listContract(currentpage);
			    	     }
			    	 }
			     
			});
		}
	});
}
//合同审核页面contractReview查询
function listContract1(currentpage){	
	
	$.ajax({
		url:'../contract/listContract',
		type:'get',                                                                                                                                                                                                                        
		data:{'currentpage':currentpage},
		dataType:'json',
		success:function(result){	
			currentpage = result.pageInfo.pageNum;
			$("#conTable1 tbody").html("");
			$.each(result.contractList,function(index,item){							
				
			var checkBoxTd = $("<td><input type='checkbox' class='check_item'></td>");			
			var conNameTd = $("<td></td>").append(item.conName);
			var conTypeTd = $("<td></td>").append(item.conType);
			var conStateTd = $("<td class='conState'></td>").append(item.conState);
			var conConLatestOpreationTimeTd = $("<td></td>").append(item.conLatestOpreationTime);
			var conNextHandlerTd = $("<td></td>").append(item.conNextHandeler);
			
			//给复选框id
			checkBoxTd.prop("contract-id",item.contractId);
			//删除按钮
			var delTd = $("<button></button>").addClass("btn btn-warning btn-xs active delete_btn").append("删除");
			delTd.attr("delete-id",item.contractId);
			var btnTd = $("<td></td>").append(delTd);
							
			$("<tr class='active'></tr>").append("<td></td")
						.append(checkBoxTd)
						.append(conNameTd)
						.append(conTypeTd)
						.append(conStateTd)
						.append(conConLatestOpreationTimeTd)
						.append(conNextHandlerTd)
						.append(btnTd)
						.appendTo("#conTable1 tbody");		
			
				
			});
			laypage({
				 cont:'reviewfenye',//容器
			     pages:result.pages, //总页数
			     //limit:2,//每页显示的条数
			     curr:currentpage,//当前页
			     skin:'molv',//皮肤
			     skip:true,//
			     last:'尾页',//
			     jump:function(obj,first){	
			    	 currentpage=obj.curr;
			    	     if(!first){
			    	    	listContract1(obj.curr)
			    	    	 }
			    	 }
			     
			});
		}
	});
}
//合同审核页面contractReview之审核
$(document).delegate('.reviewBtn', 'click', function() {
	theArray = [];
	//将所有的input修改为readonly
	$("#reviewContract input").attr("readonly","readonly");
	$("#reviewContract textarea").attr("readonly","readonly");
	//拿到复选框中的合同id
	$(".check_item:checked").each(function() { 
		 theArray.push($(this).parents("td").prop("contract-id"));
		 console.log("////////"+theArray[0]);		    
	 });
		   
	 if(theArray.length!=1){
		   jBox.tip("请选择一个进行审核","warning");
	 }else{
		getState(theArray[0]);
		console.log("state:"+state);
		if(state=="已提交"){
			 getContract(theArray[0]);
			 $('#reviewContract').modal('show');
			 $("body").css("padding-right",0);
		}else{		
			jBox.tip("非法审核！","warning");
		}			
	 }	
});


//删除合同
//单个删除
$(document).on("click",".delete_btn",function(){
	alert("删除合同");
	var contractId = $(this).attr("delete-id");
	if (confirm("确认删除吗？")) {
		$.ajax({
			url:'../contract/delContract',
			type:'post',
			data:{'contractId':contractId},
			success:function(result){
				//提示删除结果
				alert(result.message);
				//删除完成后返回页面数据
				listContract(currentpage);
			}
		})
	}
})

//contractReview之查看合同
//点击查看按钮弹出模态框，查看合同
$(document).delegate('.lookBtn', 'click', function() {
	theArray = [];
	//将所有的input修改为readonly
	$("#lookContract input,#lookContract textarea").attr("disabled","disabled");
	//拿到复选框中的合同id
	$(".check_item:checked").each(function() { 
		   theArray.push($(this).parents("td").prop("contract-id"));
		   console.log("////////"+theArray[0]);		    
	 });
		   
	 if(theArray.length!=1){
		   jBox.tip("请选择一个查看","warning");
	 }else{
		 getContract(theArray[0]);
		 $('#lookContract').modal('show');
		 $("body").css("padding-right",0);			
	 }
	
});
//contractTable之编辑模态框通过ID查询合同
function getContract(contractId){
	$.ajax({
		url:'../contract/getContract',
		type:'get',
		data:{'contractId':contractId},
		dataType:'json',
		success:function(contract){
			var c = contract;
			//编辑，查看
			$("#contractId2").val(c.contractId);
			$("#conName2").val(c.conName);
			$("#optionType").val(c.conType);
			$("#optionType").text(c.conType);
			$("#optionType2").text(c.conType);
			$("#optionType2").val(c.conType);
			$("#conPrice2").val(c.conPrice);
			$("#conPartyA2").val(c.conPartyA);
			$("#conPartyB2").val(c.conPartyB);
			$("#conBusinessNumA2").val(c.conBusinessNumA);
			$("#conBusinessNumB2").val(c.conBusinessNumB);
			$("#conContext2").val(c.conContext);
			$("#conRemark2").val(c.conRemark);	
			$("#conCreater2").val(c.conCreater);
			//审核
			$("#contractId3").val(c.contractId);
			$("#conName3").val(c.conName);
			$("#optionType3").val(c.conType);
			$("#optionType3").text(c.conType);
			$("#conPrice3").val(c.conPrice);
			$("#conPartyA3").val(c.conPartyA);
			$("#conPartyB3").val(c.conPartyB);
			$("#conBusinessNumA3").val(c.conBusinessNumA);
			$("#conBusinessNumB3").val(c.conBusinessNumB);
			$("#conContext3").val(c.conContext);
			$("#conRemark3").val(c.conRemark);	
			$("#conCreater3").val(c.conCreater);
		}	
	});
}
//通过ID查询合同状态
var state = "";
function getState(contractId){
	$.ajax({
			url:'../contract/getContract',
			type:'get',
			async:false,//同步
			data:{'contractId':contractId},
			dataType:'json',
			success:function(contract){
				state = contract.conState;
				console.log("状态："+state);
			}	
	});

}


//编辑修改合同
//点击弹出模态框，修改合同
$(document).delegate('.edit_btn', 'click', function() {
	var contractId = $(this).attr("edit-id");
	/*//3、把编辑按钮得到的员工ID传递给模态框的更新按钮
	$("#btnUpdateSubmit").attr("edit-id",contractId);*/
	getContract(contractId);
	$('#updateContract').modal('show');
	$("body").css("padding-right",0);
	
});

//点击模态框中的 确认修改按钮
$(document).delegate('#btnUpdateSubmit', 'click', function() {
	$('#updateContract').modal('hide');
	$.ajax({
		url : '../contract/updateContract',
		async : true,
		type : 'post',
		dataType : "text",
		data:$("#updateContractForm").serialize(),
		cache : false, // 不允许缓存
		success : function(result) {
			if (result == "success") {				
				jBox.tip("修改成功!!","success");
				listContract(currentpage);
			} else {
				jBox.tip("修改失败!!","error");
			}

		},
		error : function(result) {
			jBox.tip("修改失败!!","error");
		}
	});
});
//contractReview之 审核模态框 之 确认按钮 点击事件 
$(document).delegate('#btnReviewOk', 'click', function(){
	$.ajax({
		url : '../contract/checkContract',
		async : true,
		type : 'post',
		dataType : "text",
		data:$("#reviewContractForm").serialize(),
		cache : false, // 不允许缓存
		success : function(result) {
			if (result == "success") {				
				jBox.tip("审核成功!!","success");
				listContract1(currentpage);
			} else {
				jBox.tip("审核失败!!","error");
			}

		},
		error : function(result) {
			jBox.tip("审核失败!!","error");
		}
	});
	$('#reviewContract').modal('hide');
})

//contractReview之 审核模态框 之 打回按钮 点击事件 ，弹出模态框填写审批意见。
$(document).delegate('#btnReviewBack', 'click', function(){
	$('#reviewContract').modal('hide');//隐藏审核模态框，弹出打回审批意见模态框
	$('#backContract').modal('show');//隐藏审核模态框，弹出审批意见模态框
})
//打回模态框 确认按钮
$(document).delegate('#btnBackOk', 'click', function(){
	$('#contractId4').val($('#contractId3').val());//打回模态框添加id
	console.log("contractId4:"+$('#contractId4').val());
	$('#backContract').modal('hide');
	$.ajax({
		url : '../contract/backContract',
		async : true,
		type : 'post',
		dataType : "text",
		data: $("#backContractForm").serialize(),
		cache : false, // 不允许缓存
		success : function(result) {
			if (result == "success") {				
				jBox.tip("打回成功!!","success");
				listContract1(currentpage);
			} else {
				jBox.tip("打回失败!!","error");
			}
		},
		error : function(result) {
			jBox.tip("打回失败!!","error");
		}
	});
});
///contractReview之 查询
$(document).delegate('.search','click',function(){
	listUwant(currentpage);
});
//分条件查询
function listUwant(currentpage){
	var conName = $("#serachConName").val();
	var conType = $("#searchConType").val();
	var conState = $("#searchConState").val();
	$.ajax({
		url : '../contract/searchContract',
		async : true,
		type : 'post',
		dataType : "json",
		data: {"conName":conName,"conType":conType,"conState":conState,"currentpage":currentpage},
		cache : false, // 不允许缓存
		success : function(result) {
			$("#conTable1 tbody").html("");
			if(result.contractList==null){
				$("#conTable1 tbody").html("未找到相关记录！");
			}
			$.each(result.contractList,function(index,item){							
				var checkBoxTd = $("<td><input type='checkbox' class='check_item'></td>");			
				var conNameTd = $("<td></td>").append(item.conName);
				var conTypeTd = $("<td></td>").append(item.conType);
				var conStateTd = $("<td class='conState'></td>").append(item.conState);
				var conConLatestOpreationTimeTd = $("<td></td>").append(item.conLatestOpreationTime);
				var conNextHandlerTd = $("<td></td>").append(item.conNextHandeler);
				
				//给复选框id
				checkBoxTd.prop("contract-id",item.contractId);
				//删除按钮
				var delTd = $("<button></button>").addClass("btn btn-warning btn-xs active delete_btn").append("删除");
				delTd.attr("delete-id",item.contractId);
				var btnTd = $("<td></td>").append(delTd);
								
				$("<tr class='active'></tr>").append("<td></td")
							.append(checkBoxTd)
							.append(conNameTd)
							.append(conTypeTd)
							.append(conStateTd)
							.append(conConLatestOpreationTimeTd)
							.append(conNextHandlerTd)
							.append(btnTd)
							.appendTo("#conTable1 tbody");		
									
			});
			laypage({
				 cont:'reviewfenye',//容器
			     pages:result.pages, //总页数
			     //limit:2,//每页显示的条数
			     curr:currentpage,//当前页
			     skin:'molv',//皮肤
			     skip:true,//
			     last:'尾页',//
			     jump:function(obj,first){		
			    	 currentpage=obj.curr;
			    	     if(!first){
			    	    	 listUwant(obj.curr)
			    	    	 }
			    	 }
			     
			});
		},
	});
}
